﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Web.Mvc;
using Confcloud.Email.Templates;
using Smarly.Core;
using Smarly.Core.Database;

namespace Smarly.Bussines.Model.Account
{
	public class NewAccount : ModelStateObject
	{
		[DatabaseValidation("EmailBusy", "Email занят")]
		[Required(ErrorMessage ="Поле не заполнено")]
		[RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$", ErrorMessage = "Значение email не корректно")]
		public string Email { get; set; }

		[Required(ErrorMessage = "Поле не заполнено")]
		[StringLength(32, MinimumLength = 6, ErrorMessage = "Минимальная длина 6 символов")]
		[RegularExpression(@"^\w+$", ErrorMessage = "Должен содержать только цифры, латинские буквы и подчеркивание")]
		public string Password { get; set; }

/*
		[RegularExpression(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$", ErrorMessage = "Должен содержать минимум одну цифру, одну большую букву и одну маленькую букву")]
*/
		[Compare("Password", ErrorMessage = "Пароли не совпадают")]
		public string RepeatPassword { get; set; }

		public string HashCode { get; set; }

		public NewAccount Post()
		{
			HashCode = null;

			if (!ModelState.IsValid)
				return this;

			Login login = new Login(){Email = Email};
			login.GetPasswordSalt();


			Password pass = new Password() {PasswordString = Password, PasswordSalt = login.PasswordSalt};
			pass.EncodePassword();

			string hash = pass.PasswordHash;
			string salt = pass.PasswordSalt;

			SqlRepository.ExecuteProcedureReader("User_Create",
			                                     new List<SpParam>
			                                     	{
			                                     		new SpParam {Name = "@email", Type = DbType.String, Value = Email},
			                                     		new SpParam {Name = "@passwordHash", Type = DbType.String, Value = hash},
			                                     		new SpParam {Name = "@passwordSalt", Type = DbType.String, Value = salt},
			                                     	},
			                                     OnSqlInfoMessage,
																					 reader => ModelState.IsValid ? ReadPost(reader) : ReadInvalidModelStatePost(reader));

			if (ModelState.IsValid)
				new CreateUserEmail(Email).Post();
			return this;
		}

		public NewAccount ReadPost(IDataReader reader)
		{
			while (reader.Read())
			{
				this.HashCode = reader.GetString("HashCode");
			}

			return this;
		}

		public NewAccount ReadInvalidModelStatePost(IDataReader reader)
		{
			return this;
		}
	}
}